<template>
  <div class='container'>
    <Breadcrumb :items="['短链管理', '我的短链']" />
    <a-card class='general-card' title='我的短链'>
      <a-row>
        <a-col :flex='1'>
          <a-form
            :model='formModel'
            :label-col-props='{ span: 6 }'
            :wrapper-col-props='{ span: 18 }'
            label-align='left'
          >
            <a-row :gutter='16'>
              <a-col :span='8'>
                <a-form-item
                  field='number'
                  label='短链接网址'
                >
                  <a-input
                    v-model='formModel.number'
                    placeholder='短链接网址'
                  />
                </a-form-item>
              </a-col>
              <a-col :span='8'>
                <a-form-item
                  field='contentType'
                  label='分组'
                >
                  <a-select
                    v-model='formModel.contentType'
                    :options='contentTypeOptions'
                    placeholder='默认分组'
                  />
                </a-form-item>
              </a-col>
              <a-col :span='8'>
                <a-form-item
                  field='createdTime'
                  :label="$t('searchTable.form.createdTime')"
                >
                  <a-range-picker
                    v-model='formModel.createdTime'
                    style='width: 100%'
                  />
                </a-form-item>
              </a-col>
              <a-col :span='8'>
                <a-form-item
                  field='status'
                  :label="$t('searchTable.form.status')"
                >
                  <a-select
                    v-model='formModel.status'
                    :options='statusOptions'
                    :placeholder="$t('searchTable.form.selectDefault')"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style='height: 84px' direction='vertical' />
        <a-col :flex="'86px'" style='text-align: right'>
          <a-space direction='vertical' :size='18'>
            <a-button type='primary' @click='search'>
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click='reset'>
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style='margin-top: 0' />
      <a-row style='margin-bottom: 16px'>
        <a-col :span='12'>
          <a-space>
            <a-button type='primary'>
              <template #icon>
                <icon-plus />
              </template>
              新建
            </a-button>
            <a-upload action='/'>
              <template #upload-button>
                <a-button>
                  批量导入
                </a-button>
              </template>
            </a-upload>
          </a-space>
        </a-col>
        <a-col
          :span='12'
          style='display: flex; align-items: center; justify-content: end'
        >
          <a-button>
            <template #icon>
              <icon-download />
            </template>
            下载
          </a-button>
          <a-tooltip content='刷新'>
            <div class='action-icon' @click='search'>
              <icon-refresh size='18' />
            </div>
          </a-tooltip>
          <a-dropdown @select='handleSelectDensity'>
            <a-tooltip content='密度'>
              <div class='action-icon'>
                <icon-line-height size='18' />
              </div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for='item in densityList'
                :key='item.value'
                :value='item.value'
                :class='{ active: item.value === size }'
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip content='列设置'>
            <a-popover
              trigger='click'
              position='bl'
              @popup-visible-change='popupVisibleChange'
            >
              <div class='action-icon'>
                <icon-settings size='18' />
              </div>
              <template #content>
                <div id='tableSetting'>
                  <div
                    v-for='(item, index) in showColumns'
                    :key='item.dataIndex'
                    class='setting'
                  >
                    <div style='margin-right: 4px; cursor: move'>
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model='item.checked'
                        @change='
                          handleChange($event, item as TableColumnData, index)
                        '
                      >
                      </a-checkbox>
                    </div>
                    <div class='title'>
                      {{ item.title === "#" ? "序列号" : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key='id'
        :loading='loading'
        :pagination='pagination'
        :columns='(cloneColumns as TableColumnData[])'
        :data='renderData'
        :bordered='false'
        :size='size'
        @page-change='onPageChange'
      >
        <template #shortLinkInfo='{ record }'>
          <a-row align='center'>
            <a-col :span='4'>
              <a-avatar :size='20' shape='square'>
                <img alt='img' :src='record.favicon' />
              </a-avatar>
            </a-col>
            <a-col :span='20'>
              <a-popover title='链接用途'>
                <span>{{ record.title }}</span>
                <div style='font-size: 10px;color: #939393'>
                  {{ record.createTime }}
                </div>
                <template #content>
                  {{ record.describe }}
                </template>
              </a-popover>
            </a-col>
          </a-row>
        </template>
        
        <template #fullShortUrl='{ record }'>
          <a-link :href='record.fullShortUrl'>{{ record.fullShortUrl }}</a-link>
        </template>
        
        <template #originUrl='{ record }'>
          <a-popover title='原始链接'>
            <div style='width: 200px;'>
              <p class='text-ellipsis'>{{ record.originUrl }}</p>
            </div>
            <template #content>
              <p>{{ record.originUrl }}</p>
            </template>
          </a-popover>
        </template>
        
        <template #pvCount='{record}' class='show-count'>
          <div class='show-count'>
            <span>今日</span>
            <span>{{ record.todayPv }}</span>
          </div>
          <div class='show-count'>
            <span>累计</span>
            <span>{{ record.totalPv }}</span>
          </div>
        </template>
        
        <template #uipCount='{record}'>
          <div class='show-count'>
            <span>今日</span>
            <span>{{ record.todayUv }}</span>
          </div>
          <div class='show-count'>
            <span>累计</span>
            <span>{{ record.totalUv }}</span>
          </div>
        </template>
        
        <template #ipCount='{record}'>
          <div class='show-count'>
            <span>今日</span>
            <span>{{ record.todayUip }}</span>
          </div>
          <div class='show-count'>
            <span>累计</span>
            <span>{{ record.totalUip }}</span>
          </div>
        </template>
        
        <template #status='{ record }'>
          <a-tag v-if='record.status === "0"' color='green'>正常</a-tag>
          <a-tag v-else color='red'>失效</a-tag>
        </template>
        
        <template #operations>
          <a-space>
            <a-button
              type='primary'
              @click='toShortLinkDetail'
              size='small'>
              详情
            </a-button>
            <a-button type='outline' size='small'>
              编辑
            </a-button>
            <a-popconfirm
              content='您确定要删除该短链吗?'
              @cancel='() => {}'
              @ok='() => {}'
              type='warning'
              position='lb'
            >
              <a-button size='small'>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    
    <!--短链接监控弹出框-->
    <ShortLinkDetail :visible='dioVisible' @close-modal='dioVisible = false'/>
  </div>
</template>

<script lang='ts' setup>
import { computed, ref, reactive, watch, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import useLoading from "@/hooks/loading";
import { queryPolicyList, PolicyRecord, PolicyParams } from "@/api/list";
import { Pagination } from "@/types/global";
import type { SelectOptionData } from "@arco-design/web-vue/es/select/interface";
import type { TableColumnData } from "@arco-design/web-vue/es/table/interface";
import cloneDeep from "lodash/cloneDeep";
import Sortable from "sortablejs";
import ShortLinkDetail from "@/views/list/search-table/components/ShortLinkDetail.vue";

type SizeProps = "mini" | "small" | "medium" | "large";
type Column = TableColumnData & { checked?: true };

const generateFormModel = () => {
  return {
    number: "",
    name: "",
    contentType: "",
    filterType: "",
    createdTime: [],
    status: ""
  };
};
const { loading, setLoading } = useLoading(true);
const { t } = useI18n();
const renderData = ref<PolicyRecord[]>([]);
const formModel = ref(generateFormModel());
const cloneColumns = ref<Column[]>([]);
const showColumns = ref<Column[]>([]);

const size = ref<SizeProps>("medium");

const basePagination: Pagination = {
  current: 1,
  pageSize: 20
};
const pagination = reactive({
  ...basePagination
});
const densityList = computed(() => [
  {
    name: "迷你",
    value: "mini"
  },
  {
    name: "偏小",
    value: "small"
  },
  {
    name: "中等",
    value: "medium"
  },
  {
    name: "偏大",
    value: "large"
  }
]);
const columns = computed<TableColumnData[]>(() => [
  {
    title: "短链接信息",
    dataIndex: "shortLinkInfo",
    slotName: "shortLinkInfo"
  },
  {
    title: "短链接网址",
    dataIndex: "fullShortUrl",
    slotName: "fullShortUrl"
  },
  {
    title: "原始网址",
    dataIndex: "originUrl",
    slotName: "originUrl"
  },
  {
    title: "访问次数",
    dataIndex: "pv",
    slotName: "pvCount"
  },
  {
    title: "访问人数",
    dataIndex: "uip",
    slotName: "uipCount"
  },
  {
    title: "IP数",
    dataIndex: "ip",
    slotName: "ipCount"
  },
  {
    title: "短链接状态",
    dataIndex: "status",
    slotName: "status"
  },
  {
    title: "操作",
    dataIndex: "operations",
    slotName: "operations"
  }
]);
const contentTypeOptions = computed<SelectOptionData[]>(() => [
  {
    label: "默认分组",
    value: "img"
  },
  {
    label: "双11营销活动",
    value: "horizontalVideo"
  },
  {
    label: "618营销活动",
    value: "verticalVideo"
  }
]);
const filterTypeOptions = computed<SelectOptionData[]>(() => [
  {
    label: t("searchTable.form.filterType.artificial"),
    value: "artificial"
  },
  {
    label: t("searchTable.form.filterType.rules"),
    value: "rules"
  }
]);
const statusOptions = computed<SelectOptionData[]>(() => [
  {
    label: "正常",
    value: "0"
  },
  {
    label: "失效",
    value: "1"
  }
]);
const fetchData = async (
  params: PolicyParams = { current: 1, pageSize: 20 }
) => {
  setLoading(true);
  try {
    // const { data } = await queryPolicyList(params);
    /*
    "id": 1820472507438780418,
    "domain": "http://tt.cn:8001",
    "shortUri": "2t4RYo",
    "fullShortUrl": "tt.cn:8001/2t4RYo",
    "originUrl": "http://nageoffer.com",
    "gid": "ckb9Sy",
    "validDateType": 0,
    "enableStatus": 0,
    "validDate": null,
    "createTime": "2024-08-05 22:50:43",
    "describe": "跳转到拿个offer吧",
    "favicon": null,
    "totalPv": 2,
    "todayPv": null,
    "totalUv": 0,
    "todayUv": null,
    "totalUip": 0,
    "todayUip": null
     */
    renderData.value = [
      {
        "id": "3",
        "title": "我的Gitee",
        "describe": "跳转到拿个offer吧",
        "favicon": "https://gitee.com/assets/favicon.ico",
        "fullShortUrl": "tt.cn:8001/g8dDt",
        "shortLinkInfo": "71",
        "originUrl": "https://gitee.com/tiantian17",
        "createTime": "2024-08-05 22:50:43",
        "status": "0",
        "totalPv": 5,
        "todayPv": 2,
        "totalUv": 2,
        "todayUv": 1,
        "totalUip": 5,
        "todayUip": 1
      },
      {
        "id": "1",
        "title": "淘宝618营销活动",
        "describe": "跳转到拿个offer吧",
        "favicon": "https://img.alicdn.com/tps/i3/T1OjaVFl4dXXa.JOZB-114-114.png",
        "fullShortUrl": "tt.cn:8001/4EyT0a",
        "shortLinkInfo": "71",
        "originUrl": "https://detail.tmall.com/item.htm?id=793014177217",
        "createTime": "2024-08-06 19:23:43",
        "status": "0",
        "totalPv": 2,
        "todayPv": 1,
        "totalUv": 2,
        "todayUv": 1,
        "totalUip": 1,
        "todayUip": 1
      },
      {
        "id": "2",
        "title": "京东618营销活动",
        "describe": "跳转到拿个offer吧",
        "favicon": "https://www.jd.com/favicon.ico",
        "fullShortUrl": "tt.cn:8001/21K8wB",
        "shortLinkInfo": "71",
        "originUrl": "https://item.jd.com/10100904577948.html?bbtf=1",
        "createTime": "2024-08-06 21:50:43",
        "status": "1",
        "totalPv": 1,
        "todayPv": 1,
        "totalUv": 1,
        "todayUv": 1,
        "totalUip": 1,
        "todayUip": 1
      }
    ];
    pagination.current = 1;
    pagination.total = 23;
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
};

const dioVisible = ref(false)
const toShortLinkDetail  = () => {
  dioVisible.value = true
  
}

const search = () => {
  fetchData({
    ...basePagination,
    ...formModel.value
  } as unknown as PolicyParams);
};
const onPageChange = (current: number) => {
  fetchData({ ...basePagination, current });
};

fetchData();
const reset = () => {
  formModel.value = generateFormModel();
};

const handleSelectDensity = (
  val: string | number | Record<string, any> | undefined,
  e: Event
) => {
  size.value = val as SizeProps;
};

const handleChange = (
  checked: boolean | (string | boolean | number)[],
  column: Column,
  index: number
) => {
  if (!checked) {
    cloneColumns.value = showColumns.value.filter(
      (item) => item.dataIndex !== column.dataIndex
    );
  } else {
    cloneColumns.value.splice(index, 0, column);
  }
};

const exchangeArray = <T extends Array<any>> (
  array: T,
  beforeIdx: number,
  newIdx: number,
  isDeep = false
): T => {
  const newArray = isDeep ? cloneDeep(array) : array;
  if (beforeIdx > -1 && newIdx > -1) {
    // 先替换后面的，然后拿到替换的结果替换前面的
    newArray.splice(
      beforeIdx,
      1,
      newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
    );
  }
  return newArray;
};

const popupVisibleChange = (val: boolean) => {
  if (val) {
    nextTick(() => {
      const el = document.getElementById("tableSetting") as HTMLElement;
      const sortable = new Sortable(el, {
        onEnd (e: any) {
          const { oldIndex, newIndex } = e;
          exchangeArray(cloneColumns.value, oldIndex, newIndex);
          exchangeArray(showColumns.value, oldIndex, newIndex);
        }
      });
    });
  }
};

watch(
  () => columns.value,
  (val) => {
    cloneColumns.value = cloneDeep(val);
    cloneColumns.value.forEach((item, index) => {
      item.checked = true;
    });
    showColumns.value = cloneDeep(cloneColumns.value);
  },
  { deep: true, immediate: true }
);
</script>

<script lang='ts'>
export default {
  name: "SearchTable"
};
</script>

<style scoped lang='less'>
.container {
  padding: 0 20px 20px 20px;
}

.show-count span:first-child {
  color: #939393;
}

.show-count span:nth-child(2) {
  color: #1d2129;
  font-weight: bolder;
  margin-left: 10px;
}


.text-ellipsis {
  margin: 0;
  padding: 0;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}

.action-icon {
  margin-left: 12px;
  cursor: pointer;
}

.active {
  color: #0960bd;
  background-color: #e3f4fc;
}

.setting {
  display: flex;
  align-items: center;
  width: 200px;
  
  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>
